package com.yanqu.road.server.manager.orewar;

import com.alibaba.fastjson.JSON;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.config.battle.BattleResult;
import com.yanqu.road.entity.crossorewar.*;
import com.yanqu.road.entity.enums.eMessageType;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.entity.player.UserPatrons;
import com.yanqu.road.logic.bussiness.cross.CrossOreWarBussiness;
import com.yanqu.road.logic.bussiness.servercenter.ActivityBussiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.logic.pb.BattlePb;
import com.yanqu.road.logic.pb.PatronsPb;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.logic.thread.ThreadTaskManger;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.cross.activity.CrossActivityProto;
import com.yanqu.road.pb.orewar.OreWarProto;
import com.yanqu.road.pb.patrons.PatronsProto;
import com.yanqu.road.pb.worldmessage.WorldMessageProto;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.logic.battle.BattleManager;
import com.yanqu.road.server.manager.activity.ActivityChatMgr;
import com.yanqu.road.server.manager.activity.ActivityMgr;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.server.pb.orewar.CrossOreWarPb;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.ConfigHelper;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.UUIDHelper;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.executor.GeneralTask;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
//跨服用的
public class CrossOreWar {

	private Logger logger = LogManager.getLogger(CrossOreWar.class.getName());

	private final Object lockObj = new Object();

	private ActivityInfo activityInfo;

	private Map<Integer, CrossOreStationInfo> crossOreStationMap;

	private CrossOreStationInfo firstCrossOreStationInfo;

	private Map<Integer, CrossOrePitInfo> crossOrePitInfoMap;

	private ThreadTaskManger threadTaskManger;

	private AtomicInteger actionId = new AtomicInteger(1);

	private Map<Integer, CrossUserOrePit> crossUserOrePitMap;//用户跨服坑位信息

	//serverId userId List
	private Map<Long, Map<Long, List<CrossOreWarRecord>>> crossOreWarRecordMap;//跨服战斗记录,登录请求所有和被打同步单条,是单个玩家的

	private LinkedList<CrossOreWarNotice> crossOreWarNoticeList;

	private List<CrossOreWarNotice> needAddNoticeList;

	private List<CrossOreWarRecord> needAddRecordList = new ArrayList<>();

	private List<CrossUserOrePit> needUpdateCrossUserOrePitList = new ArrayList<>();

	private RandomHelper random = new RandomHelper();

	private long blowoutTime = 0;//井喷的触发时间点

	private boolean isReload = false;//在重启或者刷新的时候不会对冠名的变化产生影响，启动的时候会导致冠名在对象中从无到有，会触发冠名奖励

	private int groupId;

	public int getGroupId() {
		return groupId;
	}

	public CrossOreWar(ActivityInfo acInfo,int groupId){
		activityInfo = acInfo;
		this.groupId = groupId;
//		reload();
	}

	/**
	 * 出现维护一天以上的跨天维护时，首先先发昨天的奖励，发完奖励后去掉坑位的井喷状态，然后再次井喷
	 */
	public void timerTask(){
		if((activityInfo.getActivityId() == 9021816 || activityInfo.getActivityId() == 9021819) && blowoutTime < 1612170000000L){
			blowoutTime = 0;
		}
		long nowTimeMilli = System.currentTimeMillis();
		systemRecall(nowTimeMilli);//先判断是否要撤回玩家发放奖励
		stopBlowoutStation(nowTimeMilli,false);//顺序不能乱，先发奖励再消失井喷
		randomBlowoutStation(nowTimeMilli);//顺序不能乱，先判断要不要停止井喷，再开始新的井喷
	}

	public boolean init() {
		return reload();
	}

	public boolean stop() {
		return false;
	}

	public boolean save() {
		List<CrossUserOrePit> tempPitList;
		synchronized (needUpdateCrossUserOrePitList) {
			tempPitList = new ArrayList<>(needUpdateCrossUserOrePitList);
			needUpdateCrossUserOrePitList = new ArrayList<>();
		}
		if (tempPitList.size() > 0) {
			CrossOreWarBussiness.updateCrossUserOrePitList(tempPitList);
		}
		//保存记录
		List<CrossOreWarRecord> tempNeedAddRecord;
		synchronized (needAddRecordList) {
			tempNeedAddRecord = new ArrayList<>(needAddRecordList);
			needAddRecordList = new ArrayList<>();
		}
		if (tempNeedAddRecord.size() > 0) {
			CrossOreWarBussiness.addCrossOreWarRecordList(tempNeedAddRecord);
		}
		List<CrossOreWarNotice> tempNeedAddNotice = new ArrayList<>();
		synchronized (needAddNoticeList){
			tempNeedAddNotice.addAll(needAddNoticeList);
			needAddNoticeList = new ArrayList<>();
		}
		if(tempNeedAddNotice.size() > 0){
			CrossOreWarBussiness.addCrossOreWarNoticeList(tempNeedAddNotice);
		}
		return true;
	}

	public ActivityInfo getActivityInfo(){
		return activityInfo;
	}

	public boolean reload() {
		isReload = true;
		crossOreStationMap = ActivityBussiness.getCrossOreWarStationInfoMap(activityInfo.getActivityId());
		if (crossOreStationMap.size() <= 0) {
			return false;
		}
		crossOrePitInfoMap = initCrossOrePitMap();
		if(crossOrePitInfoMap.size() <= 0){
			return false;
		}

		threadTaskManger = new ThreadTaskManger(4, "crossOreWarTaskManger");
		crossUserOrePitMap = CrossOreWarBussiness.getCrossUserOrePitMap(activityInfo.getActivityId(),getGroupId());
		boolean isChange = false;
		if(crossUserOrePitMap.size() < crossOrePitInfoMap.size()){
			CrossOreWarBussiness.initCrossUserOrePitMap(crossOrePitInfoMap, crossUserOrePitMap, getGroupId());
			isChange = true;
		}
		if(isChange){
			crossUserOrePitMap = CrossOreWarBussiness.getCrossUserOrePitMap(activityInfo.getActivityId(),getGroupId());
		}

		refreshCrossOreStation();
		//加载记录信息
		crossOreWarRecordMap = CrossOreWarBussiness.getCrossOreWarRecordMap(activityInfo.getActivityId(),getGroupId());
		needAddRecordList = new ArrayList<>();

		//加载通告信息
		crossOreWarNoticeList = CrossOreWarBussiness.getCrossOreWarNoticeList(activityInfo.getActivityId(),getGroupId(),GameConfig.MINE_WAR_MAX_NOTICE_COUNT);
		needAddNoticeList = new ArrayList<>();

		isReload = false;
		return true;
	}

	//侦查玩家
	public List<CrossUserOrePit> getCrossUserOrePitListByAliasId(long aliasId){
		List<CrossUserOrePit> pitList = new ArrayList<>();
		for(CrossUserOrePit crossUserOrePit : crossUserOrePitMap.values()){
			if(crossUserOrePit.getUserBaseInfo().getUserAliasId() == aliasId){
				pitList.add(crossUserOrePit);
			}
		}
		return pitList;
	}

	//返回第一个建筑的所有坑位信息
	public List<CrossUserOrePit> getCrossTopBuildingOrePitList(){
		List<CrossUserOrePit> res = new ArrayList<>();
		for(int index = 1;index <= firstCrossOreStationInfo.getPitCount();index ++){
			res.add(crossUserOrePitMap.get(index));
		}
		return res;
	}

	//根据坑位信息，返回随机权重中的一个坑位
	private int randomWeightBlowout(List<Integer> stationIdList){
		int randomStationId = 0;
		int allWeight = 0;
		for(Integer stationId : stationIdList){
			allWeight += crossOreStationMap.get(stationId).getBlowoutWeight();
		}
		int randomValue = random.next(0,allWeight);
		for(Integer stationId : stationIdList){
			if(randomValue < crossOreStationMap.get(stationId).getBlowoutWeight()){
				randomStationId = stationId;
				break;
			}
			randomValue = randomValue - crossOreStationMap.get(stationId).getBlowoutWeight();

		}
		return randomStationId;
	}

	//随机井喷资源点
	private void randomBlowoutStation(long nowTimeMilli){
		List<Integer> blowoutList = new ArrayList<>();
		boolean checkIsBlowout = false;
		if(DateHelper.getZeroTimeStamp(blowoutTime) != DateHelper.getZeroTimeStamp(nowTimeMilli)){
			List<Integer> blowoutParamList = StringUtils.stringToIntegerList(activityInfo.getParam4(),"\\|");
			long startMinute = blowoutParamList.get(0);
			int blowoutNum = blowoutParamList.get(1);
			if(nowTimeMilli >= DateHelper.getZeroTimeStamp(nowTimeMilli) + startMinute * 60 * 1000){
				List<Integer> tempList = new ArrayList<>();
				for(int stationId : crossOreStationMap.keySet()){
					tempList.add(stationId);
					if(crossOreStationMap.get(stationId).isBlowout()){
						checkIsBlowout = true;
					}
				}
				if(!checkIsBlowout){
					for(int i = 0;i<blowoutNum;i++){
						int randomStationId = randomWeightBlowout(tempList);
						blowoutList.add(randomStationId);
						tempList.remove(new Integer(randomStationId));
					}
					//去通知各个服务器发送井喷的消息了
                    if(CrossOreWarActivityMgr.getInTimeActivityInfo(activityInfo.getActivityId()) != null){
//                        OreWarProto.CrossNotifyBlowoutMessage.Builder respMsg = CrossOreWarPb.parseCrossNotifyBlowoutMsg(activityInfo.getActivityId(),getGroupId());
//                        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_CROSS_ORE_WAR_BLOWOUT_NOTIFY, respMsg);
//                        syncServer(pbMsg);
						WorldMessageProto.WorldMessageTempMsg.Builder msg = WorldMessageProto.WorldMessageTempMsg.newBuilder();
						msg.setActivityId(activityInfo.getActivityId());
						msg.setType(eMessageType.OreWarBlowout.getValue());

						msg.setContent("");
						msg.setSendTime(System.currentTimeMillis() / 1000);
						msg.setGroupId(groupId);
						ActivityChatMgr.activityChat(activityInfo.getActivityId(), msg.build());
                    }
				}
				blowoutTime = nowTimeMilli;
			}
			List<CrossUserOrePit> needSyncPit = new ArrayList<>();
			if(blowoutList.size() > 0){
				//所有坑位先清除井喷状态
				for(CrossUserOrePit crossUserOrePit : crossUserOrePitMap.values()){
					crossUserOrePit.setBlowout(false);
				}
				//井喷之前先结算没有井喷前的奖励
				blowoutStartReward(blowoutList);
				for (Integer stationId : blowoutList){
					for(CrossUserOrePit crossUserOrePit : crossUserOrePitMap.values()){
						if(crossUserOrePit.getStationId() == stationId){
							crossUserOrePit.setBlowout(true);
							synchronized (needUpdateCrossUserOrePitList) {
								if (!needUpdateCrossUserOrePitList.contains(crossUserOrePit)) {
									needUpdateCrossUserOrePitList.add(crossUserOrePit);
								}
							}
                            needSyncPit.add(crossUserOrePit);
						}
					}
				}
			}
			syncCrossOrePit(needSyncPit,false);
			refreshCrossOreStation();
		}
	}


	/**
	 * 	//结束井喷
	 * @param force boolean 强制结束，判断要撤回的时候会强制结束，有可能维护了一天导致还是在井喷时间内，通过坑位的玩家加入时间来判断井喷，理论上不可能出现坑上都没人的情况
	 */
	private void stopBlowoutStation(long nowTimeMilli ,boolean force){
		List<Integer> blowoutParamList = StringUtils.stringToIntegerList(activityInfo.getParam4(),"\\|");//开始井喷的时间分钟|井喷的个数
		long startBlowoutMinute = blowoutParamList.get(0);
		long startBlowoutTime = DateHelper.getZeroTimeStamp(nowTimeMilli) + startBlowoutMinute * 60 * 1000;
		List<Integer> acList = StringUtils.stringToIntegerList(activityInfo.getParam6(),"\\|");//活动开始在当天的分钟|活动结束在当天的分钟
		long endDayMinute = acList.get(1);
		long endDayTime = DateHelper.getZeroTimeStamp(nowTimeMilli) + endDayMinute * 60 * 1000;
		List<CrossUserOrePit> needSyncPit = new ArrayList<>();
		if(nowTimeMilli < startBlowoutTime || nowTimeMilli > endDayTime || force){
			for(CrossUserOrePit crossUserOrePit : crossUserOrePitMap.values()){
				crossUserOrePit.setBlowout(false);
				synchronized (needUpdateCrossUserOrePitList) {
					if (!needUpdateCrossUserOrePitList.contains(crossUserOrePit)) {
						needUpdateCrossUserOrePitList.add(crossUserOrePit);
					}
				}
				needSyncPit.add(crossUserOrePit);
			}
			refreshCrossOreStation();
		}
		syncCrossOrePit(needSyncPit,false);
	}

	//更新用户的基础信息数据，冠名的时候要用到，更新完之后要重新刷新下
	public void updateBaseUserInfo(Map<Long,UserBaseInfo> infoMap){
		List<CrossUserOrePit> syncList = new ArrayList<>();
		for(long userId : infoMap.keySet()){
			List<CrossUserOrePit> crossUserOrePitList = getCrossUserOrePitList(userId);
			for(CrossUserOrePit crossUserOrePit : crossUserOrePitList){
				crossUserOrePit.setNickName(infoMap.get(userId).getNickName());
				crossUserOrePit.setUserBaseInfo(infoMap.get(userId));
			}
			syncList.addAll(crossUserOrePitList);
		}
		syncCrossOrePit(syncList,false);
	}

	//刷新坑位信息
	public void refreshCrossOreStation(){
		for(CrossOreStationInfo crossOreStationInfo : getCrossOreStationMap().values()){
			changeCrossOreStation(crossOreStationInfo);
		}
	}


	public void patronsAbilityChange(long userId,UserBaseInfo userBaseInfo, int pitId,
									 List<UserPatrons> userPatronsList,int beautySkillAddition,int patronsSkillAddition) {
		CrossUserOrePit crossUserOrePit = getCrossUserOrePit(pitId);
		if(null == crossUserOrePit || crossUserOrePit.getUserId() != userId){
			return;
		}
		//修复数据
		if(crossUserOrePit.getPatronsList().size() > GameConfig.MINE_WAR_BATTLE_MAX_PATRONS_COUNT){
			crossUserOrePit.setPatronsInfoStr(JSON.toJSONString(userPatronsList));
		}
		//只更新不增加
		List<UserPatrons> updatePatronsList = userPatronsList;
		if(crossUserOrePit.getPatronsList().size() != userPatronsList.size()){
			Map<Integer,UserPatrons> oreWarPatronMap = new ConcurrentHashMap<>();
			for(UserPatrons oreWarPatrons : crossUserOrePit.getPatronsList()){
				oreWarPatronMap.put(oreWarPatrons.getPatronsId(),oreWarPatrons);
			}
			for(UserPatrons syncPatrons : userPatronsList){
				if(oreWarPatronMap.containsKey(syncPatrons.getPatronsId())){
					oreWarPatronMap.put(syncPatrons.getPatronsId(),syncPatrons);
				}
			}
			updatePatronsList = new ArrayList<>(oreWarPatronMap.values());
			patronsSkillAddition = crossUserOrePit.getPatronsSkillAddition();
			//重新下发一条校验本服门客信息
			List<CrossUserOrePit> crossPitList  = CrossOreWarMgr.getCrossUserOrePitList(activityInfo.getActivityId(),crossUserOrePit.getUserId(),groupId);
			OreWarProto.CrossOrePitListMsg.Builder respMsg = CrossOreWarPb.parseCrossOrePitListMsg(crossPitList);
			respMsg.setActivityId(activityInfo.getActivityId());
			YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_CROSS_ORE_WAR_SELF_PIT, respMsg);
			MessageHelper.sendPacket(crossUserOrePit.getServerId(), crossUserOrePit.getUserId(), pbMsg);
		}

		crossUserOrePit.setNickName(userBaseInfo.getNickName());//更新基础信息
		crossUserOrePit.setPatronsList(updatePatronsList);
		crossUserOrePit.setPatronsInfoStr(JSON.toJSONString(updatePatronsList));
		crossUserOrePit.setUserBaseInfo(userBaseInfo);
		crossUserOrePit.setBeautySkillAddition(beautySkillAddition);
		crossUserOrePit.setPatronsSkillAddition(patronsSkillAddition);
		//更新能力
		crossUserOrePit.setTotalAbility();
		syncCrossOrePit(crossUserOrePit);
		synchronized (needUpdateCrossUserOrePitList) {
			if (!needUpdateCrossUserOrePitList.contains(crossUserOrePit)) {
				needUpdateCrossUserOrePitList.add(crossUserOrePit);
			}
		}
		CrossOreStationInfo crossOreStationInfo = getCrossOreStationInfo(crossUserOrePit.getStationId());
		changeCrossOreStation(crossOreStationInfo);
	}


	public void patronsAbilityChange(long userId,UserBaseInfo userBaseInfo, List<OreWarProto.CrossOreWarPatronsSyncMsg> patronsMsgList) {
		for (OreWarProto.CrossOreWarPatronsSyncMsg patronsSyncMsg : patronsMsgList) {
			int pitId = patronsSyncMsg.getPitId();
			CrossUserOrePit crossUserOrePit = getCrossUserOrePit(pitId);
			synchronized (lockObj) {
				if(null == crossUserOrePit || crossUserOrePit.getUserId() != userId){
					return;
				}
				String patronsInfoStr = patronsSyncMsg.getPatronsInfoStr();
				List<UserPatrons> userPatronsList = JSON.parseArray(patronsInfoStr,UserPatrons.class);
				int patronsSkillAddition = patronsSyncMsg.getPatronsSkillAddition();
				int beautySkillAddition = patronsSyncMsg.getBeautySkillAddition();
				//修复数据
				if(crossUserOrePit.getPatronsList().size() > GameConfig.MINE_WAR_BATTLE_MAX_PATRONS_COUNT){
					crossUserOrePit.setPatronsInfoStr(JSON.toJSONString(userPatronsList));
				}
				//只更新不增加
				List<UserPatrons> updatePatronsList = userPatronsList;
				if(crossUserOrePit.getPatronsList().size() != userPatronsList.size()){
					Map<Integer,UserPatrons> oreWarPatronMap = new ConcurrentHashMap<>();
					for(UserPatrons oreWarPatrons : crossUserOrePit.getPatronsList()){
						oreWarPatronMap.put(oreWarPatrons.getPatronsId(),oreWarPatrons);
					}
					for(UserPatrons syncPatrons : userPatronsList){
						if(oreWarPatronMap.containsKey(syncPatrons.getPatronsId())){
							oreWarPatronMap.put(syncPatrons.getPatronsId(),syncPatrons);
						}
					}
					updatePatronsList = new ArrayList<>(oreWarPatronMap.values());
					patronsSkillAddition = crossUserOrePit.getPatronsSkillAddition();
					//重新下发一条校验本服门客信息
					List<CrossUserOrePit> crossPitList  = CrossOreWarMgr.getCrossUserOrePitList(activityInfo.getActivityId(),crossUserOrePit.getUserId(),groupId);
					OreWarProto.CrossOrePitListMsg.Builder respMsg = CrossOreWarPb.parseCrossOrePitListMsg(crossPitList);
					respMsg.setActivityId(activityInfo.getActivityId());
					YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_CROSS_ORE_WAR_SELF_PIT, respMsg);
					MessageHelper.sendPacket(crossUserOrePit.getServerId(), crossUserOrePit.getUserId(), pbMsg);
				}

				crossUserOrePit.setNickName(userBaseInfo.getNickName());//更新基础信息
				crossUserOrePit.setPatronsList(updatePatronsList);
				crossUserOrePit.setPatronsInfoStr(JSON.toJSONString(updatePatronsList));
				crossUserOrePit.setUserBaseInfo(userBaseInfo);
				crossUserOrePit.setBeautySkillAddition(beautySkillAddition);
				crossUserOrePit.setPatronsSkillAddition(patronsSkillAddition);
				//更新能力
				crossUserOrePit.setTotalAbility();
			//	syncCrossOrePit(crossUserOrePit);
			}
			synchronized (needUpdateCrossUserOrePitList) {
				if (!needUpdateCrossUserOrePitList.contains(crossUserOrePit)) {
					needUpdateCrossUserOrePitList.add(crossUserOrePit);
				}
			}
			CrossOreStationInfo crossOreStationInfo = getCrossOreStationInfo(crossUserOrePit.getStationId());
			changeAverageAbilityAndOccupyCount(crossOreStationInfo);
		}
	}

	//撤回玩家的坑位
	public OreWarProto.CrossOrePitRecallRespMsg.Builder orePitRecall(long userId,UserBaseInfo userBaseInfo, int pitId){
		OreWarProto.CrossOrePitRecallRespMsg.Builder msg = OreWarProto.CrossOrePitRecallRespMsg.newBuilder();
		Property occupyReward;
		CrossUserOrePit crossUserOrePit;
		long nowTime = System.currentTimeMillis() / 1000;
		synchronized (lockObj) {
			crossUserOrePit = getCrossUserOrePit(pitId);
			if (null == crossUserOrePit) {
				msg.setRet(GameErrorCode.E_ORE_WAR_ORE_PIT_NO_FOUND);
				return msg;
			}
			if(crossUserOrePit.getUserId() != userId){
				msg.setRet(GameErrorCode.E_MINE_WAR_MINE_PIT_OWNER_CHANGE);
				return msg;
			}
			//防止商会信息变了没有更新导致冠名没有算进去结算奖励
            crossUserOrePit.setUserBaseInfo(userBaseInfo);
            occupyReward = getPitOccupyReward(userId, crossUserOrePit, nowTime, true);
			msg.setPatronsInfoStr(crossUserOrePit.getPatronsInfoStr());
			//清除状态
			clearOrePitUser(crossUserOrePit);
		}


		//矿场资源
		int goodsId = GameConfig.ACTIVITY_ORE_WAR_OUTPUT_GOODSID;
		msg.setRet(0);
		msg.setActivityId(activityInfo.getActivityId());
		msg.setPitId(pitId);
		msg.setReward(occupyReward.getCountByGoodsId(goodsId).intValue());
		msg.setGroupId(groupId);
		return msg;
	}

	public void syncCrossStation(CrossOreStationInfo oreStationInfo,boolean isAllSync){
		List<CrossOreStationInfo> syncList = new ArrayList<>();
		syncList.add(oreStationInfo);
		OreWarProto.CrossOreStationSyncMsg.Builder respMsg = CrossOreWarPb.parseCrossStationSyncMsg(activityInfo.getActivityId(),syncList,getGroupId());
		respMsg.setIsAllSync(isAllSync);
		YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_CROSS_ORE_WAR_PIT_STATION_SYNC, respMsg);
		syncServer(pbMsg);
	}

	public void syncAllCrossStation(long serverId){
		List<CrossOreStationInfo> syncList = new ArrayList<>(crossOreStationMap.values());
		OreWarProto.CrossOreStationSyncMsg.Builder respMsg = CrossOreWarPb.parseCrossStationSyncMsg(activityInfo.getActivityId(),syncList,getGroupId());
		respMsg.setIsAllSync(true);
		YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_CROSS_ORE_WAR_PIT_STATION_SYNC, respMsg);
		MessageHelper.sendPacket(serverId, 0, pbMsg);
	}

	//同步跨服的坑位信息变化给各个区服
	public void syncCrossOrePit(List<CrossUserOrePit> syncList,boolean isAllSync){
		OreWarProto.CrossOrePitSyncMsg.Builder respMsg = CrossOreWarPb.parseCrossOrePitSyncMsg(activityInfo.getActivityId(),syncList);
		respMsg.setIsAllSync(isAllSync);
		YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_CROSS_ORE_WAR_PIT_SYNC, respMsg);
//		syncServer(pbMsg);
	}

	public void sendAllUserPit(long serverId){
		List<CrossUserOrePit> syncList = new ArrayList<>(crossUserOrePitMap.values());
		OreWarProto.CrossOrePitSyncMsg.Builder respMsg = CrossOreWarPb.parseCrossOrePitSyncMsg(activityInfo.getActivityId(),syncList);
		respMsg.setIsAllSync(true);
		YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_CROSS_ORE_WAR_PIT_SYNC, respMsg);
//		MessageHelper.sendChannelPacket(serverId, 0, pbMsg);
	}

	public void sendAllNotice(long serverId){
		List<CrossOreWarNotice> syncList = new LinkedList<>(crossOreWarNoticeList);
		OreWarProto.CrossNoticeSyncMsg.Builder respMsg = CrossOreWarPb.parseCrossOreWarNoticeSyncMsg(activityInfo.getActivityId(),syncList,getGroupId());
		respMsg.setIsAllSync(true);
		YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_CROSS_ORE_WAR_NOTICE_SYNC, respMsg);
		MessageHelper.sendPacket(serverId, 0, pbMsg);
	}

	public void sendAllRecord(long serverId){
		List<CrossOreWarRecord> allRecordList = new ArrayList<>();
		Map<Long,List<CrossOreWarRecord>> recordMap = crossOreWarRecordMap.get(serverId);
		Map<Long,List<CrossOreWarRecord>> syncMap = new ConcurrentHashMap<>();
		if(null != recordMap){
			syncMap = new ConcurrentHashMap<>(recordMap);
		}
		for(List<CrossOreWarRecord> recordList : syncMap.values()){
			allRecordList.addAll(recordList);
		}
		OreWarProto.CrossRecordSyncMsg.Builder respMsg = CrossOreWarPb.parseCrossRecordSyncMsg(activityInfo.getActivityId(),allRecordList,getGroupId());
		respMsg.setIsAllSync(true);
		YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_CROSS_ORE_WAR_RECORD_SYNC, respMsg);
		MessageHelper.sendPacket(serverId, 0, pbMsg);
	}

	public void syncCrossOrePit(CrossUserOrePit syncOrePit){
        List<CrossUserOrePit> syncList = new ArrayList<>();
        syncList.add(syncOrePit);
		OreWarProto.CrossOrePitSyncMsg.Builder respMsg = CrossOreWarPb.parseCrossOrePitSyncMsg(activityInfo.getActivityId(),syncList);
		respMsg.setIsAllSync(false);
		YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_CROSS_ORE_WAR_PIT_SYNC, respMsg);
//		syncServer(pbMsg);
	}

	public void syncCrossOrePit(int pitId){
		CrossUserOrePit syncOrePit = crossUserOrePitMap.get(pitId);
        List<CrossUserOrePit> syncList = new ArrayList<>();
        syncList.add(syncOrePit);
		OreWarProto.CrossOrePitSyncMsg.Builder respMsg = CrossOreWarPb.parseCrossOrePitSyncMsg(activityInfo.getActivityId(),syncList);
		respMsg.setIsAllSync(false);
		YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_CROSS_ORE_WAR_PIT_SYNC, respMsg);
//		syncServer(pbMsg);
	}

	public void syncCrossNotice(CrossOreWarNotice syncNotice){
        List<CrossOreWarNotice> syncList = new ArrayList<>();
        syncList.add(syncNotice);
		OreWarProto.CrossNoticeSyncMsg.Builder respMsg = CrossOreWarPb.parseCrossOreWarNoticeSyncMsg(activityInfo.getActivityId(),syncList,getGroupId());
		respMsg.setIsAllSync(false);
		YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_CROSS_ORE_WAR_NOTICE_SYNC, respMsg);
		syncServer(pbMsg);
	}

	private void syncServer(YanQuMessage pbMsg){
		List<Long> serverIdList = activityInfo.getServerIdList();
		for(long serverId : serverIdList){
			MessageHelper.sendPacket(serverId, 0, pbMsg);
		}
	}

	//活动的每日激活时间
	public boolean isActivityActive(){
		List<Integer> acList = StringUtils.stringToIntegerList(activityInfo.getParam6(),"\\|");//活动开始在当天的分钟|活动结束在当天的分钟
		long startMinute = acList.get(0);
		long endMinute = acList.get(1);
		if(System.currentTimeMillis() < DateHelper.getTodayZeroTimeStamp() + startMinute*60*1000
				|| System.currentTimeMillis() > DateHelper.getTodayZeroTimeStamp() + endMinute*60*1000){
			return false;
		}
		return true;
	}

	public void systemRecall(long nowTimeMilli){
        long endTime = activityInfo.getEndTime();
        if (nowTimeMilli / 1000 - endTime > 10 * 60) {
            return;
        }
        List<Integer> acList = StringUtils.stringToIntegerList(activityInfo.getParam6(),"\\|");//活动开始在当天的分钟|活动结束在当天的分钟
		long toadyZeroTime = DateHelper.getZeroTimeStamp(nowTimeMilli)/1000;
		long startSec = acList.get(0) * 60 + toadyZeroTime;
		long endSec = acList.get(1) * 60 + toadyZeroTime;
		long nowTime = nowTimeMilli/1000;
		long targetTime = 0;//以这个作为基准时间来判断加入多少时间的需要撤回，考虑到更新服务器停服一天的情况导致过了休战期
		if(nowTime >= startSec){
			targetTime = startSec;
		}
		if(nowTime >= endSec){
			targetTime = endSec;
		}
		//按照人头进行撤回
		List<Long> userIdList = new ArrayList<>();
		for(CrossUserOrePit crossUserOrePit : crossUserOrePitMap.values()){
			//加入时间不对就是要撤回的
			if(crossUserOrePit.getJoinTime() <= targetTime && crossUserOrePit.getUserId() != 0 && !userIdList.contains(crossUserOrePit.getUserId())){
				userIdList.add(crossUserOrePit.getUserId());
			}
		}
		boolean isRecall = false;
		if(userIdList.size() > 0){
			isRecall = true;
		}
		for(long userId : userIdList){
			if(userId != 0){
				systemOrePitRecall(userId,nowTimeMilli);
				//do-xx 撤回的时候本服要同步在线玩家撤回后的坑位
				/*GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
				if(player != null){
					player.sendChannelPacket(Protocol.U_ORE_WAR_MY_PIT_LIST, OreWarPb.parseMyOrePitListMsg(new ArrayList<>(), false));
				}*/
			}
		}
		//监测到要撤回就一定要停止当前的井喷状态
		if(isRecall){
			refreshCrossOreStation();
			stopBlowoutStation(nowTimeMilli,true);
		}
	}

	//系统撤回玩家坑位(包括争霸坑位和避难所的坑位)
	private void systemOrePitRecall(long userId,long nowTimeMilli){
		List<CrossUserOrePit> needSyncPit = new ArrayList<>();
		long serverId = 0;
		if(userId == 0){
			return;
		}
		Property systemRecallReward = new Property();
		long nowTime = nowTimeMilli / 1000;
		synchronized (lockObj) {
			for(CrossUserOrePit crossUserOrePit : crossUserOrePitMap.values()){
				if(crossUserOrePit.getUserId() == userId){
					//计算占领收益
					long lastGetRewardTime = crossUserOrePit.getLastGetRewardTime();
					Property tempReward = getPitOccupyReward(userId,crossUserOrePit, nowTime, true);
					systemRecallReward.addProperty(tempReward);
					serverId = crossUserOrePit.getServerId();
					//用这个清除会导致冠名变化，后面撤回的玩家变成冠名奖励
//					clearOrePitUser(crossUserOrePit);
					recallClearOrePitUser(crossUserOrePit);
					needSyncPit.add(crossUserOrePit);
					//do-xx 系统撤回本服奖励记录 没有单条的记录了
					/*LogMgr.addLogOreWarReward(userId, crossUserOrePit.getActivityId(), crossUserOrePit.getPitId(), PropertyHelper.parsePropertyToString(tempReward),
							nowTime - lastGetRewardTime, false, eLogMoneyType.OreWarPitRecall.getValue());*/
				}
			}
		}
		//发送到本服
		if(!systemRecallReward.isNothing() && serverId != 0){
			OreWarProto.CrossSystemRecallMailMsg.Builder respMsg = CrossOreWarPb.parseCrossSystemRecallMailMsg(activityInfo.getActivityId(),userId,systemRecallReward,nowTime,needSyncPit,getGroupId());
			YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_CROSS_ORE_SYSTEM_RECALL_MAIL, respMsg);
			MessageHelper.sendPacket(serverId, 0, pbMsg);
		}
	}

	//玩家井喷或者冠名变化时候同步给本服自己的坑位信息
	private void syncUserOrePitChange(List<CrossUserOrePit> crossUserOrePitList){
		//serverId userId 要同步用户的自己坑位的信息给客户端
		Map<Long,Map<Long,List<CrossUserOrePit>>> syncMap = new ConcurrentHashMap<>();
		for(CrossUserOrePit crossUserOrePit : crossUserOrePitList){
			//把需要同步的整理了
			if(!syncMap.containsKey(crossUserOrePit.getServerId())){
				syncMap.put(crossUserOrePit.getServerId(),new ConcurrentHashMap<>());
			}
			Map<Long,List<CrossUserOrePit>> userMap = syncMap.get(crossUserOrePit.getServerId());
			if(!userMap.containsKey(crossUserOrePit.getUserId())){
				userMap.put(crossUserOrePit.getUserId(),new ArrayList<>());
			}
			userMap.get(crossUserOrePit.getUserId()).add(crossUserOrePit);
		}
		for(Long serverId : syncMap.keySet()){
			Map<Long,List<CrossUserOrePit>> userMap = syncMap.get(serverId);
			for (Long userId : userMap.keySet()){
				List<CrossUserOrePit> crossPitList = userMap.get(userId);
				OreWarProto.CrossOrePitListMsg.Builder respMsg = CrossOreWarPb.parseCrossOrePitListMsg(crossPitList);
				respMsg.setActivityId(activityInfo.getActivityId());
				YanQuMessage pbSyncMsg = YanQuMessageUtils.buildMessage(Protocol.S_CROSS_ORE_WAR_SELF_PIT_SYNC, respMsg);
				MessageHelper.sendPacket(serverId, userId, pbSyncMsg);
			}
		}
	}

	//井喷之前要之前的奖励结算给玩家然后再开始井喷
	private void blowoutStartReward(List<Integer> stationIdList){
		//要同步用户的自己坑位的信息给客户端
		List<CrossUserOrePit> syncList = new ArrayList<>();
		//serverId
		Map<Long,OreWarProto.CrossBlowoutMailMsg.Builder> sendMap = new ConcurrentHashMap<>();
		long nowTime = System.currentTimeMillis()/1000;
		synchronized (lockObj) {
			for(CrossUserOrePit crossUserOrePit : crossUserOrePitMap.values()){
				if(stationIdList.contains(crossUserOrePit.getStationId()) && crossUserOrePit.getUserId() != 0){
					//计算占领收益
					Property tempReward = getPitOccupyReward(crossUserOrePit.getUserId(), crossUserOrePit, nowTime, true);
					if(!tempReward.isNothing()){
						//把需要同步的整理了
						syncList.add(crossUserOrePit);
						// 给每日开始井喷的据点上的用户发送没有井喷前的奖励,全部发送到对应本服中去发放
						if(!sendMap.containsKey(crossUserOrePit.getServerId())){
							OreWarProto.CrossBlowoutMailMsg.Builder blowoutMailMsg = OreWarProto.CrossBlowoutMailMsg.newBuilder();
							blowoutMailMsg.setActivityId(activityInfo.getActivityId());
							blowoutMailMsg.setGroupId(getGroupId());
							sendMap.put(crossUserOrePit.getServerId(),blowoutMailMsg);
						}
						OreWarProto.CrossBlowoutMailTempMsg.Builder tempMsg = OreWarProto.CrossBlowoutMailTempMsg.newBuilder();
						tempMsg.setUserId(crossUserOrePit.getUserId());
						tempMsg.setPitId(crossUserOrePit.getPitId());
						tempMsg.setReward(PropertyHelper.parsePropertyToString(tempReward));
						sendMap.get(crossUserOrePit.getServerId()).addMail(tempMsg);
					}
				}
			}
			syncUserOrePitChange(syncList);
			for(long serverId : sendMap.keySet()){
				YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_CROSS_ORE_SYSTEM_BLOWOUT_MAIL, sendMap.get(serverId));
				MessageHelper.sendPacket(serverId, 0, pbMsg);
			}
		}

	}

	/**
	 * 清除矿坑占有状态
	 * @param crossUserOrePit
	 */
	private void clearOrePitUser(CrossUserOrePit crossUserOrePit) {
		if (null == crossUserOrePit) {
			return;
		}
		//玩家坑位被撤回清空同步门客占领信息
		/*GamePlayer player = GamePlayerMgr.getOnlinePlayer(userOrePit.getUserId());
		updateOrePitPatronsState(player, userOrePit, OreWarMgr.DISPATCH_ORE_NONE);*/
		crossUserOrePit.setActivityId(activityInfo.getActivityId());
		crossUserOrePit.setUserId(0);
		crossUserOrePit.setServerId(0);
		crossUserOrePit.setNickName("");
		crossUserOrePit.setPatronsInfoStr("[]");
		crossUserOrePit.setBeautySkillAddition(0);
		crossUserOrePit.setPatronsSkillAddition(0);
		crossUserOrePit.setPatronsList(new ArrayList<>());
		crossUserOrePit.setTotalAbility();
		crossUserOrePit.setUserBaseInfo(new UserBaseInfo());
		crossUserOrePit.setLastGetRewardTime(System.currentTimeMillis() / 1000);
		synchronized (needUpdateCrossUserOrePitList) {
			if (!needUpdateCrossUserOrePitList.contains(crossUserOrePit)) {
				needUpdateCrossUserOrePitList.add(crossUserOrePit);
			}
		}
		CrossOreStationInfo crossOreStationInfo = getCrossOreStationInfo(crossUserOrePit.getStationId());
		if(null != crossOreStationInfo){
			changeCrossOreStation(crossOreStationInfo);
		}
		//do-xx 同步坑位的信息給区服区服再看看对应的玩家是否在线同步给对应的玩家
		syncCrossOrePit(crossUserOrePit);
	}

	private void recallClearOrePitUser(CrossUserOrePit crossUserOrePit) {
		if (null == crossUserOrePit) {
			return;
		}
		crossUserOrePit.setActivityId(activityInfo.getActivityId());
		crossUserOrePit.setUserId(0);
		crossUserOrePit.setServerId(0);
		crossUserOrePit.setNickName("");
		crossUserOrePit.setPatronsInfoStr("[]");
		crossUserOrePit.setBeautySkillAddition(0);
		crossUserOrePit.setPatronsSkillAddition(0);
		crossUserOrePit.setPatronsList(new ArrayList<>());
		crossUserOrePit.setTotalAbility();
		crossUserOrePit.setUserBaseInfo(new UserBaseInfo());
		crossUserOrePit.setLastGetRewardTime(System.currentTimeMillis() / 1000);
		synchronized (needUpdateCrossUserOrePitList) {
			if (!needUpdateCrossUserOrePitList.contains(crossUserOrePit)) {
				needUpdateCrossUserOrePitList.add(crossUserOrePit);
			}
		}
	}

	//返回用户的坑位信息????
	public List<CrossUserOrePit> getCrossUserOrePitList(int startPitId, int endPitId){
		List<CrossUserOrePit> pitList = new ArrayList<>();
		if(null != crossUserOrePitMap){
			for(int i = startPitId; i <= endPitId; i++){
				pitList.add(crossUserOrePitMap.get(i));
			}
		}
		return pitList;
	}

	public List<CrossUserOrePit> getCrossUserOrePitList(long userId){
		List<CrossUserOrePit> pitList = new ArrayList<>();
		for(CrossUserOrePit crossUserOrePit : crossUserOrePitMap.values()){
			if(crossUserOrePit.getUserId() == userId){
				pitList.add(crossUserOrePit);
			}
		}
		return pitList;
	}

	private List<CrossUserOrePit> getCrossUserOrePitList(int stationId){
		List<CrossUserOrePit> pitList = new ArrayList<>();
		for(CrossUserOrePit crossUserOrePit : crossUserOrePitMap.values()){
			if(crossUserOrePit.getStationId() == stationId){
				pitList.add(crossUserOrePit);
			}
		}
		return pitList;
	}

	public CrossUserOrePit getCrossUserOrePit(int pitId){
		return crossUserOrePitMap.get(pitId);
	}

	public Map<Integer, CrossOreStationInfo> getCrossOreStationMap() {
		return crossOreStationMap;
	}

	public CrossOreStationInfo getCrossOreStationInfo(int crossOreStationId){
		if(crossOreStationMap.containsKey(crossOreStationId)){
			return crossOreStationMap.get(crossOreStationId);
		}
		return null;
	}

	public Map<Integer, CrossOrePitInfo> getCrossOrePitInfoMap() {
		return crossOrePitInfoMap;
	}

	public CrossOrePitInfo getCrossOrePitInfo(int pitId) {
		if(crossOrePitInfoMap.containsKey(pitId)){
			return crossOrePitInfoMap.get(pitId);
		}
		return null;
	}

	/**
	 * 按照ID规则生成矿坑地图信息
	 */
	private Map<Integer, CrossOrePitInfo> initCrossOrePitMap() {
		Map<Integer, CrossOrePitInfo> totalCrossOrePitInfoMap = new ConcurrentHashMap<>();
		int pitId = 1;
		int minStationId = Integer.MAX_VALUE;
		for(CrossOreStationInfo stationInfo : getCrossOreStationMap().values()){
			if(stationInfo.getStationId() < minStationId)minStationId = stationInfo.getStationId();
			for (int index = 0; index < stationInfo.getPitCount(); index++) {
				CrossOrePitInfo pitInfo = new CrossOrePitInfo();
				pitInfo.setActivityId(stationInfo.getActivityId());
				pitInfo.setName(stationInfo.getStationName());
				pitInfo.setStationId(stationInfo.getStationId());
				pitInfo.setPitId(pitId);
				pitInfo.setPitIndex(index + 1);
				pitInfo.setOutputSpeedAddition(stationInfo.getOutputSpeedAddition() + stationInfo.getAddOutputSpeedAddition() * (stationInfo.getPitCount() - index - 1));
				pitId++;
				totalCrossOrePitInfoMap.put(pitInfo.getPitId(), pitInfo);
			}
		}
		firstCrossOreStationInfo = getCrossOreStationMap().get(minStationId);
		return totalCrossOrePitInfoMap;
	}

	public BigDecimal getCrossOreOutput(CrossUserOrePit crossUserOrePit, int oreAddition,int unionAddition){
		if(null == crossUserOrePit.getPatronsList()){
			return BigDecimal.ZERO;
		}
		double beautySkillAddition = crossUserOrePit.getBeautySkillAddition();
		double patronsSkillAddition = crossUserOrePit.getPatronsSkillAddition();
		BigDecimal totalValue = BigDecimal.valueOf(oreAddition);
		totalValue = totalValue.multiply(BigDecimal.valueOf((patronsSkillAddition + beautySkillAddition + unionAddition) / 1000 + 1)).multiply(BigDecimal.valueOf(crossUserOrePit.getPatronsList().size())).
				setScale(0, BigDecimal.ROUND_UP);
		return totalValue;
	}

	/**
	 * 抢夺矿坑
	 */
	public OreWarProto.CrossOrePitRobRespMsg.Builder robPit(long userId, UserBaseInfo userBaseInfo, int pitId, long pitOwnerUserId,
															String patronsInfoStr,int beautySkillAddition,int patronsSkillAddition,int refugeCount){
		OreWarProto.CrossOrePitRobRespMsg.Builder msg = OreWarProto.CrossOrePitRobRespMsg.newBuilder();
		msg.setActivityId(activityInfo.getActivityId());
		msg.setGroupId(getGroupId());
		List<UserPatrons> patronsList = JSON.parseArray(patronsInfoStr,UserPatrons.class);
		if(patronsList.size() > GameConfig.MINE_WAR_BATTLE_MAX_PATRONS_COUNT){
			msg.setRet(GameErrorCode.E_ORE_WAR_PATRONS_COUNT_OVER);
			return msg;
		}
		//校验门客是否重复派遣
		List<CrossUserOrePit> crossUserOrePitList = getCrossUserOrePitList(userId);
		for (CrossUserOrePit crossUserOrePit : crossUserOrePitList){
			for(UserPatrons userPatrons : crossUserOrePit.getPatronsList()){
				for(UserPatrons userPatronsRob : patronsList){
					if(userPatrons.getPatronsId() == userPatronsRob.getPatronsId()){
						msg.setRet(GameErrorCode.E_ORE_WAR_PATRONS_HAS_DISPATCH);
						return msg;
					}
				}
			}
		}
		//检测矿坑是否存在
		CrossOrePitInfo pitInfo = crossOrePitInfoMap.get(pitId);
		if(null == pitInfo){
			msg.setRet(GameErrorCode.E_ORE_WAR_ORE_PIT_NO_FOUND);
			return msg;
		}
		CrossUserOrePit crossUserOrePit = crossUserOrePitMap.get(pitId);
		if(null == crossUserOrePit){
			msg.setRet(GameErrorCode.E_ORE_WAR_ORE_PIT_NO_FOUND);
			return msg;
		}
		if(crossUserOrePit.getUserId() == userId){
			msg.setRet(GameErrorCode.E_ORE_WAR_ORE_CAN_NO_ROB_SELF_PIT);
			return msg;
		}

		//do-xx 坑位已经不是之前的坑位了，去本服处理吧
		if(crossUserOrePit.getUserId() != pitOwnerUserId){//矿坑占有人发生变化
			msg.setRet(GameErrorCode.E_ORE_WAR_ORE_PIT_OWNER_CHANGE);
			OreWarProto.CrossOrePitTempMsg.Builder pitMsg = CrossOreWarPb.parseCrossOrePitTempMsg(crossUserOrePit);
			if(null != pitMsg) {
				msg.setCrossOrePit(pitMsg);
			}
			return msg;
		}

		int pitCount = getCrossUserOrePitList(userId).size();
		if(pitCount + refugeCount >= GameConfig.ACTIVITY_ORE_WAR_OCCUPY_LIMIT){
			msg.setRet(GameErrorCode.E_ORE_WAR_OCCUPY_LIMIT);
			return msg;
		}

		Property winReward = null;
		BattleResult battleResult;
		synchronized (lockObj) {
			crossUserOrePit = getCrossUserOrePit(pitId);
			//没人占领或者无限坑
			if (crossUserOrePit.getUserId() == 0) {
				//添加通告
				if(getCrossOreStationInfo(crossUserOrePit.getStationId()).isNotice()){
					CrossOreWarNotice crossOreWarNotice = initCrossOreWarNotice(crossUserOrePit,userId,userBaseInfo);
					addCrossOreWarNotice(crossOreWarNotice);
				}
				winReward = updateOrePitUser(userId,userBaseInfo, crossUserOrePit, patronsList,beautySkillAddition,patronsSkillAddition);
				msg.setRet(0);
				msg.setWinReward(PropertyHelper.parsePropertyToString(winReward));
				msg.setWinUserId(userId);
				msg.setPatronsInfoStr(patronsInfoStr);
				OreWarProto.CrossOrePitTempMsg.Builder pitMsg = CrossOreWarPb.parseCrossOrePitTempMsg(crossUserOrePit);
				if(null != pitMsg){
					msg.setCrossOrePit(pitMsg);
				}
				return msg;
			}
			UserBaseInfo enemyUserBaseInfo = crossUserOrePit.getUserBaseInfo();
			battleResult = BattleManager.battle(userId, patronsList, crossUserOrePit.getUserId(), crossUserOrePit.getPatronsList(), 0);

			boolean isWin = false;
			if (battleResult.getWinUserId() == userId) {
				isWin = true;
			}

			//添加记录
			CrossOreWarRecord crossOreWarRecord = initOreWarRecord(crossUserOrePit.getUserId(), crossUserOrePit, isWin, userId,userBaseInfo,getGroupId());
			addCrossOreWarRecord(crossOreWarRecord);

			//添加通告
			if((getCrossOreStationInfo(crossUserOrePit.getStationId()).isNotice() || !StringUtils.isNullOrEmpty(enemyUserBaseInfo.getUnionUid())) && isWin){
				CrossOreWarNotice crossOreWarNotice = initCrossOreWarNotice(crossUserOrePit, userId, userBaseInfo);
				addCrossOreWarNotice(crossOreWarNotice);
			}
			// 赢的话 替换阵容
			if (isWin) {
				long serverId = crossUserOrePit.getServerId();
				long loserUserId = crossUserOrePit.getUserId();
				OreWarProto.CrossOrePitRobLoserRespMsg.Builder loserMsg = OreWarProto.CrossOrePitRobLoserRespMsg.newBuilder();
				loserMsg.setActivityId(activityInfo.getActivityId());
				loserMsg.setPitId(crossUserOrePit.getPitId());
				loserMsg.setUserId(loserUserId);
				loserMsg.setPatronsInfoStr(crossUserOrePit.getPatronsInfoStr());
				loserMsg.setEnemyUserId(userId);
				loserMsg.setEnemyBaseData(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
				loserMsg.setEnemyPatronsInfoStr(patronsInfoStr);
				Property enemyReward = getPitOccupyReward(crossUserOrePit.getUserId(), crossUserOrePit, System.currentTimeMillis() / 1000, true);
				loserMsg.setReward(PropertyHelper.parsePropertyToString(enemyReward));

				winReward = updateOrePitUser(userId,userBaseInfo, crossUserOrePit, patronsList,beautySkillAddition,patronsSkillAddition);
				// 同步地块信息
				OreWarProto.CrossOrePitTempMsg.Builder pitMsg = CrossOreWarPb.parseCrossOrePitTempMsg(crossUserOrePit);
				if(null != pitMsg){
					msg.setCrossOrePit(pitMsg);
				}
				msg.setWinUserId(userId);
				//发送给失败者
				loserMsg.setCrossOrePit(pitMsg);
				loserMsg.setGroupId(getGroupId());
				YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_CROSS_ORE_WAR_ROBPIT_LOSER, loserMsg);
				MessageHelper.sendPacket(serverId, loserUserId, pbMsg);
			}else {
				msg.setWinUserId(crossUserOrePit.getUserId());
			}
		}
		msg.setRet(0);
		msg.setWinReward(PropertyHelper.parsePropertyToString(winReward));
		//我方信息
		msg.setPatronsInfoStr(patronsInfoStr);
		//战斗详细信息
		msg.setBattleDetailList(BattlePb.parseBattleDetailListMsg(battleResult.getPatronsBattleDetailList()));
		//对手出战门客、座骑
		for (UserPatrons userPatrons : battleResult.getEnemyPatronsList()) {
			PatronsProto.PatronsTempMsg.Builder patronsMsg = PatronsPb.parsePatronsTempMsg(userPatrons);
			if(null != patronsMsg) {
				msg.addEnemyPatronsList(patronsMsg);
			}
		}
		return msg;
	}

	private void addCrossOreWarRecord(CrossOreWarRecord crossOreWarRecord) {
		if(null == crossOreWarRecord){
			return;
		}
		synchronized (crossOreWarRecordMap) {
			if (!crossOreWarRecordMap.containsKey(crossOreWarRecord.getServerId())) {
				crossOreWarRecordMap.put(crossOreWarRecord.getServerId(), new ConcurrentHashMap<>());
			}
			if (!crossOreWarRecordMap.get(crossOreWarRecord.getServerId()).containsKey(crossOreWarRecord.getUserId())) {
				crossOreWarRecordMap.get(crossOreWarRecord.getServerId()).put(crossOreWarRecord.getUserId(), new ArrayList<>());
			}
		}
		List<CrossOreWarRecord> recordList = crossOreWarRecordMap.get(crossOreWarRecord.getServerId()).get(crossOreWarRecord.getUserId());
		synchronized (recordList) {
			if (recordList.size() >= GameConfig.MINE_WAR_MAX_RECORD_COUNT) {
				recordList.remove(0);
			}
			recordList.add(crossOreWarRecord);
		}
		synchronized (needAddRecordList) {
			needAddRecordList.add(crossOreWarRecord);
		}
		//do-xx 同步给服务器，服务器再同步给相关的用户的记录，
		//只要发对应的区服的信息就可以了
		OreWarProto.CrossRecordSyncMsg.Builder syncMsg = CrossOreWarPb.parseCrossRecordSyncMsg(activityInfo.getActivityId(),crossOreWarRecord,getGroupId());
		syncMsg.setIsAllSync(false);
		YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_CROSS_ORE_WAR_RECORD_SYNC, syncMsg);
		MessageHelper.sendPacket(crossOreWarRecord.getServerId(), crossOreWarRecord.getUserId(), pbMsg);
	}


	private static CrossOreWarRecord initOreWarRecord(long userId, CrossUserOrePit crossUserOrePit, boolean isWin, long enemyUserId ,UserBaseInfo enemyUserBaseInfo,int groupId) {
		if(null == enemyUserBaseInfo){
			return null;
		}
		if(null == crossUserOrePit){
			return null;
		}

		CrossOreWarRecord record = new CrossOreWarRecord();
		record.setUserId(userId);
		record.setServerId(crossUserOrePit.getServerId());
		record.setRecordUid(UUIDHelper.randomUUID(String.valueOf(crossUserOrePit.getServerId())));
		record.setActivityId(crossUserOrePit.getActivityId());
		record.setPitId(crossUserOrePit.getPitId());
		record.setEnemyUserId(enemyUserId);
		record.setEnemyBaseData(enemyUserBaseInfo);
		record.setRecordTime(System.currentTimeMillis() / 1000);
		record.setWin(isWin);
		record.setGroupId(groupId);
		return record;
	}

	//只有抢占的时候用到
	private Property updateOrePitUser(long userId,UserBaseInfo userBaseInfo, CrossUserOrePit crossUserOrePit,
									  List<UserPatrons> patronsList,int beautySkillAddition,int patronsSkillAddition){
		if(0 == userId || null == crossUserOrePit || null == patronsList){
			return null;
		}
		Property reward;
		long nowTime = System.currentTimeMillis() / 1000;
		crossUserOrePit.setUserId(userId);
		crossUserOrePit.setServerId(userBaseInfo.getServerId());
		crossUserOrePit.setNickName(userBaseInfo.getNickName());
		crossUserOrePit.setPatronsInfoStr(JSON.toJSONString(patronsList));
		crossUserOrePit.setBeautySkillAddition(beautySkillAddition);
		crossUserOrePit.setPatronsSkillAddition(patronsSkillAddition);
		crossUserOrePit.setPatronsList(patronsList);
		crossUserOrePit.setJoinTime(nowTime);
		crossUserOrePit.setLastGetRewardTime(nowTime);
		crossUserOrePit.setTotalAbility();
		crossUserOrePit.setUserBaseInfo(userBaseInfo);
		synchronized (needUpdateCrossUserOrePitList) {
			if (!needUpdateCrossUserOrePitList.contains(crossUserOrePit)) {
				needUpdateCrossUserOrePitList.add(crossUserOrePit);
			}
		}
		CrossOreStationInfo stationInfo = getCrossOreStationInfo(crossUserOrePit.getStationId());
		if(null != stationInfo){
			long oldSeverId = stationInfo.getServerId();
			String oldUid = stationInfo.getUnionUid();
			int oldOccupyCount = stationInfo.getOccupyCount();
			changeCrossOreStation(stationInfo);
			//分享卡通知，必须坑位都是满的情况下
			//do-xx 发送给本服本服在同步坑位的時候自己算一下or定協議下發？
			if(stationInfo.getOccupyCount() == stationInfo.getPitCount()){
				if(!stationInfo.getUnionUid().equals(oldUid)){
					OreWarProto.CrossNamingGetMessage.Builder getMsg = OreWarProto.CrossNamingGetMessage.newBuilder();
					getMsg.setActivityId(activityInfo.getActivityId());
					getMsg.setStationId(stationInfo.getStationId());
					getMsg.setUserId(userId);
					getMsg.setUnionUid(stationInfo.getUnionUid());
					getMsg.setGroupId(getGroupId());
					YanQuMessage pbGetMsg = YanQuMessageUtils.buildMessage(Protocol.S_CROSS_ORE_NAMING_GET_MESSAGE, getMsg);
					MessageHelper.sendPacket(userBaseInfo.getServerId(), 0, pbGetMsg);

					if(!stationInfo.getUnionUid().equals(oldUid)){
						OreWarProto.CrossNamingLoseMessage.Builder loseMsg = OreWarProto.CrossNamingLoseMessage.newBuilder();
						loseMsg.setActivityId(activityInfo.getActivityId());
						loseMsg.setStationId(stationInfo.getStationId());
						loseMsg.setEnemyBaseData(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
						loseMsg.setOldUnionUid(oldUid);
						loseMsg.setGroupId(getGroupId());
						YanQuMessage pbLoseMsg = YanQuMessageUtils.buildMessage(Protocol.S_CROSS_ORE_NAMING_LOSE_MESSAGE, loseMsg);
						MessageHelper.sendPacket(oldSeverId, 0, pbLoseMsg);
					}
				}
			}
		}
		//计算占领收益
		reward = getPitOccupyReward(userId, crossUserOrePit, nowTime + GameConfig.MINE_WAR_VICTORY_REWARD, false);
		return reward;
	}

	//返回用户占领坑位的奖励
	public OreWarProto.CrossOreGetRewardRespMsg.Builder getSelfPitOccupyReward(long userId){
		OreWarProto.CrossOreGetRewardRespMsg.Builder respMsg = OreWarProto.CrossOreGetRewardRespMsg.newBuilder();
		long getRewardTime = System.currentTimeMillis() / 1000;
		Property occupyReward = new Property();
		List<CrossUserOrePit> crossUserPitList = getCrossUserOrePitList(userId);
		for(CrossUserOrePit crossUserOrePit : crossUserPitList){
			long lastGetRewardTime = crossUserOrePit.getLastGetRewardTime();
			Property reward = getPitOccupyReward(userId,crossUserOrePit, getRewardTime, true);
			occupyReward.addProperty(reward);
		}
		respMsg.setActivityId(activityInfo.getActivityId());
		respMsg.setLastGetTime(getRewardTime);
		respMsg.setOutputCount1(occupyReward.getCountByGoodsId(GameConfig.ACTIVITY_ORE_WAR_OUTPUT_GOODSID).longValue());
		respMsg.setRet(0);
		respMsg.setGroupId(getGroupId());
		return respMsg;
	}

	/**
	 * 领取矿坑占领时间收益
	 */
	public Property getPitOccupyReward(long userId, CrossUserOrePit crossUserOrePit, long getRewardTime, boolean isUpdateRewardTime) {
		Property occupyReward = new Property();
		if(null == crossUserOrePit){
			logger.warn("getPitOccupyReward userOreData is null");
			return occupyReward;
		}
		if(crossUserOrePit.getUserId() != userId){
			logger.warn("getPitOccupyReward userOreData userId not same");
			return occupyReward;
		}
		CrossOrePitInfo pitInfo = getCrossOrePitInfo(crossUserOrePit.getPitId());
		long occupyTime = (getRewardTime - crossUserOrePit.getLastGetRewardTime()) / 60;
		if(occupyTime > 0){//算钱咯
			int unionAddition = 0;
			UserBaseInfo userBaseInfo = crossUserOrePit.getUserBaseInfo();
			if(userBaseInfo != null && !StringUtils.isNullOrEmpty(userBaseInfo.getUnionUid()) && crossOreStationMap.get(crossUserOrePit.getStationId()).getUnionUid().equals(userBaseInfo.getUnionUid())){
				//时间大于当前的时间就是加上了占领奖励时间，不能算商会冠名奖励
				if(getRewardTime <= System.currentTimeMillis()/1000){
					unionAddition = GameConfig.ACTIVITY_ORE_WAR_UNION_NAMING_ADD;
				}
			}
			BigInteger rewardValue = getCrossOreOutput(crossUserOrePit, pitInfo.getOutputSpeedAddition(),unionAddition).
					multiply(BigDecimal.valueOf(occupyTime)).toBigInteger();
			int goodsId = GameConfig.ACTIVITY_ORE_WAR_OUTPUT_GOODSID;
			if(goodsId > 0){
				occupyReward.addProperty(goodsId, rewardValue);
			}
			if(isUpdateRewardTime) {
				crossUserOrePit.setLastGetRewardTime(getRewardTime);
				synchronized (needUpdateCrossUserOrePitList) {
					if (!needUpdateCrossUserOrePitList.contains(crossUserOrePit)) {
						needUpdateCrossUserOrePitList.add(crossUserOrePit);
					}
				}
			}
		}
		//井喷
		if(crossUserOrePit.isBlowout()){
			occupyReward.rideProperty(BigDecimal.valueOf(GameConfig.ACTIVITY_ORE_WAR_BLOWOUT_ADD).
					divide(BigDecimal.valueOf(1000),3,BigDecimal.ROUND_UP).add(BigDecimal.ONE));
		}
		//更新坑位信息给对应区服
		syncCrossOrePit(crossUserOrePit);
		return occupyReward;
	}

	//把商会冠名和井喷设置上去
	private void setBlowNamingStation(CrossOreStationInfo oreStationInfo,boolean needSync){
		synchronized (oreStationInfo) {
			boolean syncFlag = needSync;
			Map<String,String> unionNameMap = new ConcurrentHashMap<>();//保存对应的unionId对应的unionName
			Map<String,Long> unionServerIdMap = new ConcurrentHashMap<>();//保存对应的unionId对应的serverId
			//union 0人数 1最后加入时间
			Map<String,List<Integer>> unionSameMap = new ConcurrentHashMap<>();
			List<CrossUserOrePit> tempPitList = getCrossUserOrePitList(oreStationInfo.getStationId());
			for(CrossUserOrePit pit : tempPitList){
				//是否是井喷状态
				if(pit.isBlowout() && !oreStationInfo.isBlowout()){
					syncFlag = true;
					oreStationInfo.setBlowout(true);
				}else if (!pit.isBlowout() && oreStationInfo.isBlowout()){
					syncFlag = true;
					oreStationInfo.setBlowout(false);
				}
				UserBaseInfo userBaseInfo = pit.getUserBaseInfo();
				if(userBaseInfo != null && !StringUtils.isNullOrEmpty(userBaseInfo.getUnionUid())){
					if(!unionSameMap.containsKey(userBaseInfo.getUnionUid())){
						unionSameMap.put(userBaseInfo.getUnionUid(),new ArrayList<>());
						unionSameMap.get(userBaseInfo.getUnionUid()).add(0,0);
						unionSameMap.get(userBaseInfo.getUnionUid()).add(1,0);
						unionNameMap.put(userBaseInfo.getUnionUid(),userBaseInfo.getUnionName());
						unionServerIdMap.put(userBaseInfo.getUnionUid(),userBaseInfo.getServerId());
					}
					unionSameMap.get(userBaseInfo.getUnionUid()).set(0,unionSameMap.get(userBaseInfo.getUnionUid()).get(0) + 1);
					if(pit.getJoinTime() > unionSameMap.get(userBaseInfo.getUnionUid()).get(1)){
						unionSameMap.get(userBaseInfo.getUnionUid()).set(1,unionSameMap.get(userBaseInfo.getUnionUid()).get(1) + 1);
					}
				}
			}
			int lastJoinTime = 0;
			int maxUserCount = 0;
			String maxUnionUid = "";
			//下面是按照人数最多和最后抢占作为冠名
			int maxSameCount = 1;
			for (String unionUid : unionSameMap.keySet()){
				if(unionSameMap.get(unionUid).get(0) > maxUserCount){
					maxUserCount = unionSameMap.get(unionUid).get(0);
					maxUnionUid = unionUid;
					maxSameCount = 1;
				}else if(unionSameMap.get(unionUid).get(0) == maxUserCount){
					maxSameCount++;
				}
			}
			if(maxSameCount != 1){
				maxUnionUid = "";
			}
			if(!maxUnionUid.equals(oreStationInfo.getUnionUid())){
				syncFlag = true;
			}
			//发送冠名变化奖励
			sendUnionNamingChangeReward(oreStationInfo.getStationId(),oreStationInfo.getUnionUid(),maxUnionUid);
			oreStationInfo.setServerId(0);
			oreStationInfo.setUnionUid("");
			oreStationInfo.setUnionName("");
			oreStationInfo.setUnionCount(0);
			oreStationInfo.setLastJoinTime(0);
			if(unionNameMap.containsKey(maxUnionUid)){
				oreStationInfo.setServerId(unionServerIdMap.get(maxUnionUid));
				oreStationInfo.setUnionUid(maxUnionUid);
				oreStationInfo.setUnionName(unionNameMap.get(maxUnionUid));
				oreStationInfo.setUnionCount(maxUserCount);
				oreStationInfo.setLastJoinTime(lastJoinTime);
			}
			if(syncFlag){
				syncCrossStation(oreStationInfo,false);
			}
		}
	}

	//判断新老商会id来判断冠名是否发生变化了
	private void sendUnionNamingChangeReward(int stationId,String oldUid,String newUid){
		//之前有商会冠名着，被打下来了，要给他结算冠名奖励
		if(!isReload && !StringUtils.isNullOrEmpty(oldUid) && !oldUid.equals(newUid)){
			sendNamingChangeReward(stationId,oldUid);
		}
		//打出冠名的商会的商会成员要把之前的结算了，然后开始计时冠名奖励
		if(!isReload && !StringUtils.isNullOrEmpty(newUid) && !oldUid.equals(newUid)){
			sendNamingChangeReward(stationId,newUid);
		}
	}

	/**
	 * //坑位的冠名发送了变化，涉及到奖励的两个家族或一个家族发放奖励
	 * @param stationId
	 * @param unionUid  获得冠名或者失去冠名的家族
	 */
	public void sendNamingChangeReward(int stationId,String unionUid){
		if(StringUtils.isNullOrEmpty(unionUid)){
			return;
		}
		//要同步用户的自己坑位的信息给客户端
		List<CrossUserOrePit> syncList = new ArrayList<>();
		Map<Long,OreWarProto.CrossNamingMailMsg.Builder> sendMap = new ConcurrentHashMap<>();
		//serverId,userId,reward
		Map<Long,Map<Long,Property>> serverRewardMap = new ConcurrentHashMap<>();
		for(CrossUserOrePit crossUserOrePit : crossUserOrePitMap.values()){
			if(crossUserOrePit.getStationId() == stationId){
				UserBaseInfo userBaseInfo = crossUserOrePit.getUserBaseInfo();
				if(userBaseInfo != null && unionUid.equals(userBaseInfo.getUnionUid())){
					if(!serverRewardMap.containsKey(crossUserOrePit.getServerId())){
						serverRewardMap.put(crossUserOrePit.getServerId(),new ConcurrentHashMap<>());
					}
					if(!serverRewardMap.get(crossUserOrePit.getServerId()).containsKey(crossUserOrePit.getUserId())){
						serverRewardMap.get(crossUserOrePit.getServerId()).put(crossUserOrePit.getUserId(),new Property());
					}
					Property reward = getPitOccupyReward(crossUserOrePit.getUserId(), crossUserOrePit,System.currentTimeMillis()/1000, true);
					serverRewardMap.get(crossUserOrePit.getServerId()).get(crossUserOrePit.getUserId()).addProperty(reward);
					syncList.add(crossUserOrePit);
				}
			}
		}

		for(long serverId : serverRewardMap.keySet()){
			if(!sendMap.containsKey(serverId)){
				OreWarProto.CrossNamingMailMsg.Builder namingMailMsg = OreWarProto.CrossNamingMailMsg.newBuilder();
				namingMailMsg.setActivityId(activityInfo.getActivityId());
				namingMailMsg.setGroupId(getGroupId());
				sendMap.put(serverId,namingMailMsg);
			}
			Map<Long,Property> userRewardMap = serverRewardMap.get(serverId);
			for(long userId : userRewardMap.keySet()){
				Property namingReward = userRewardMap.get(userId);
				if(!namingReward.isNothing()){
					OreWarProto.CrossNamingMailTempMsg.Builder tempMsg = OreWarProto.CrossNamingMailTempMsg.newBuilder();
					tempMsg.setUserId(userId);
					tempMsg.setStationId(stationId);
					tempMsg.setReward(PropertyHelper.parsePropertyToString(namingReward));
					sendMap.get(serverId).addMail(tempMsg);
				}
			}
		}
		syncUserOrePitChange(syncList);
		for(long serverId : sendMap.keySet()){
			YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_CROSS_ORE_NAMING_REWARD_MAIL, sendMap.get(serverId));
			MessageHelper.sendPacket(serverId, 0, pbMsg);
		}
	}

	//商会解散的时候这个商会要是是冠名状态要结算
	public void sendUnionDismissNamingChangeReward(String unionUid){
		if(StringUtils.isNullOrEmpty(unionUid)){
			return;
		}
		//要同步用户的自己坑位的信息给客户端
		List<CrossUserOrePit> syncList = new ArrayList<>();
		Map<Long,OreWarProto.CrossNamingMailMsg.Builder> sendMap = new ConcurrentHashMap<>();
		//serverId userId stationId reward
		Map<Long,Map<Long,Map<Integer,Property>>> serverRewardMap = new ConcurrentHashMap<>();
		for(CrossUserOrePit crossUserOrePit : crossUserOrePitMap.values()){
			String stationUid = crossOreStationMap.get(crossUserOrePit.getStationId()).getUnionUid();
			if(stationUid.equals(unionUid)){
				if(!serverRewardMap.containsKey(crossUserOrePit.getServerId())){
					serverRewardMap.put(crossUserOrePit.getServerId(),new ConcurrentHashMap<>());
				}
				if(!serverRewardMap.get(crossUserOrePit.getServerId()).containsKey(crossUserOrePit.getUserId())){
					serverRewardMap.get(crossUserOrePit.getServerId()).put(crossUserOrePit.getUserId(),new ConcurrentHashMap<>());
				}
				if(!serverRewardMap.get(crossUserOrePit.getServerId()).get(crossUserOrePit.getUserId()).containsKey(crossUserOrePit.getStationId())){
					serverRewardMap.get(crossUserOrePit.getServerId()).get(crossUserOrePit.getUserId()).put(crossUserOrePit.getStationId(),new Property());
				}
				Property reward = getPitOccupyReward(crossUserOrePit.getUserId(), crossUserOrePit, System.currentTimeMillis()/1000, true);
				serverRewardMap.get(crossUserOrePit.getServerId()).get(crossUserOrePit.getUserId()).get(crossUserOrePit.getStationId()).addProperty(reward);
				syncList.add(crossUserOrePit);
			}
		}
		for(long serverId : serverRewardMap.keySet()){
			if(!sendMap.containsKey(serverId)){
				OreWarProto.CrossNamingMailMsg.Builder namingMailMsg = OreWarProto.CrossNamingMailMsg.newBuilder();
				namingMailMsg.setActivityId(activityInfo.getActivityId());
				namingMailMsg.setGroupId(getGroupId());
				sendMap.put(serverId,namingMailMsg);
			}
			for(long userId : serverRewardMap.get(serverId).keySet()){
				for(int stationId : serverRewardMap.get(serverId).get(userId).keySet()){
					Property namingReward = serverRewardMap.get(serverId).get(userId).get(stationId);
					if(!namingReward.isNothing()){
						OreWarProto.CrossNamingMailTempMsg.Builder tempMsg = OreWarProto.CrossNamingMailTempMsg.newBuilder();
						tempMsg.setUserId(userId);
						tempMsg.setStationId(stationId);
						tempMsg.setReward(PropertyHelper.parsePropertyToString(namingReward));
						sendMap.get(serverId).addMail(tempMsg);
					}
				}
			}
		}
		syncUserOrePitChange(syncList);
		for(long serverId : sendMap.keySet()){
			YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_CROSS_ORE_NAMING_REWARD_MAIL, sendMap.get(serverId));
			MessageHelper.sendPacket(serverId, 0, pbMsg);
		}
	}

	//用户被踢出商会或者自己退出或者加入商会要判断他的坑位所在的建筑是不是冠名状态，是的话发送奖励
	public void sendUnionNamingJoinQuitReward(String unionUid, long userId){
		if(StringUtils.isNullOrEmpty(unionUid)){
			return;
		}
		//要同步用户的自己坑位的信息给客户端
		List<CrossUserOrePit> syncList = new ArrayList<>();
		Map<Long,OreWarProto.CrossNamingMailMsg.Builder> sendMap = new ConcurrentHashMap<>();
		//serverId stationId reward
		Map<Long,Map<Integer,Property>> serverRewardMap = new ConcurrentHashMap<>();
		List<CrossUserOrePit> crossUserOrePitList = getCrossUserOrePitList(userId);
		for(CrossUserOrePit crossUserOrePit : crossUserOrePitList){
			String stationUid = crossOreStationMap.get(crossUserOrePit.getStationId()).getUnionUid();
			if(stationUid.equals(unionUid)){
				if(!serverRewardMap.containsKey(crossUserOrePit.getServerId())){
					serverRewardMap.put(crossUserOrePit.getServerId(),new ConcurrentHashMap<>());
				}
				if(!serverRewardMap.get(crossUserOrePit.getServerId()).containsKey(crossUserOrePit.getStationId())){
					serverRewardMap.get(crossUserOrePit.getServerId()).put(crossUserOrePit.getStationId(),new Property());
				}
				Property reward = getPitOccupyReward(crossUserOrePit.getUserId(), crossUserOrePit, System.currentTimeMillis()/1000, true);
				serverRewardMap.get(crossUserOrePit.getServerId()).get(crossUserOrePit.getStationId()).addProperty(reward);
				syncList.add(crossUserOrePit);
			}
		}
		for(long serverId : serverRewardMap.keySet()){
			if(!sendMap.containsKey(serverId)){
				OreWarProto.CrossNamingMailMsg.Builder namingMailMsg = OreWarProto.CrossNamingMailMsg.newBuilder();
				namingMailMsg.setActivityId(activityInfo.getActivityId());
				namingMailMsg.setGroupId(getGroupId());
				sendMap.put(serverId,namingMailMsg);
			}
			for(int stationId : serverRewardMap.get(serverId).keySet()){
				Property namingReward = serverRewardMap.get(serverId).get(stationId);
				if(!namingReward.isNothing()){
					OreWarProto.CrossNamingMailTempMsg.Builder tempMsg = OreWarProto.CrossNamingMailTempMsg.newBuilder();
					tempMsg.setUserId(userId);
					tempMsg.setStationId(stationId);
					tempMsg.setReward(PropertyHelper.parsePropertyToString(namingReward));
					sendMap.get(serverId).addMail(tempMsg);
				}
			}
		}
		syncUserOrePitChange(syncList);
		for(long serverId : sendMap.keySet()){
			YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_CROSS_ORE_NAMING_REWARD_MAIL, sendMap.get(serverId));
			MessageHelper.sendPacket(serverId, 0, pbMsg);
		}
	}

	//更改占领人数
	public void changeCrossOreStation(CrossOreStationInfo crossOreStationInfo) {
		boolean needSync = false;
		List<CrossUserOrePit> tempPitList = getCrossUserOrePitList(crossOreStationInfo.getStationId());
		BigInteger totalAbility = BigInteger.ZERO;
		int occupyCount = 0;
		for(CrossUserOrePit pit : tempPitList){
			if(pit.getUserId() != 0){
				occupyCount++;
				if(crossOreStationInfo.isShowAbility()) {
					totalAbility = totalAbility.add(pit.getTotalAbility());
				}
			}
		}
		if(crossOreStationInfo.isShowAbility() && occupyCount >= GameConfig.MINE_WAR_OCCUPY_PIT_COUNT_SHOW_ABILITY){
			crossOreStationInfo.setAverageAbility(totalAbility.divide(BigInteger.valueOf(occupyCount)));
		}else {
			crossOreStationInfo.setAverageAbility(BigInteger.ZERO);
		}
		if(crossOreStationInfo.getOccupyCount() != occupyCount){
			needSync = true;
		}
		crossOreStationInfo.setOccupyCount(occupyCount);
		setBlowNamingStation(crossOreStationInfo,needSync);
	}

	public void changeAverageAbilityAndOccupyCount(CrossOreStationInfo crossOreStationInfo) {
		List<CrossUserOrePit> tempPitList = getCrossUserOrePitList(crossOreStationInfo.getStationId());
		BigInteger totalAbility = BigInteger.ZERO;
		int occupyCount = 0;
		for(CrossUserOrePit pit : tempPitList){
			if(pit.getUserId() != 0){
				occupyCount++;
				if(crossOreStationInfo.isShowAbility()) {
					totalAbility = totalAbility.add(pit.getTotalAbility());
				}
			}
		}
		if(crossOreStationInfo.isShowAbility() && occupyCount >= GameConfig.MINE_WAR_OCCUPY_PIT_COUNT_SHOW_ABILITY){
			crossOreStationInfo.setAverageAbility(totalAbility.divide(BigInteger.valueOf(occupyCount)));
		}else {
			crossOreStationInfo.setAverageAbility(BigInteger.ZERO);
		}
		crossOreStationInfo.setOccupyCount(occupyCount);
	}

	private void addCrossOreWarNotice(CrossOreWarNotice notice) {
		if(null == notice){
			return;
		}
		synchronized (crossOreWarNoticeList) {
			if(crossOreWarNoticeList.size() >= GameConfig.MINE_WAR_MAX_NOTICE_COUNT){
				crossOreWarNoticeList.removeFirst();
			}
			crossOreWarNoticeList.addLast(notice);
			needAddNoticeList.add(notice);
		}
		syncCrossNotice(notice);
	}

	private CrossOreWarNotice initCrossOreWarNotice(CrossUserOrePit crossUserOrePit, long userId,UserBaseInfo userBaseInfo){
		if(null == crossUserOrePit || userId <= 0){
			return null;
		}
		if(null == userBaseInfo){
			return null;
		}
		CrossOreWarNotice crossOreWarNotice = new CrossOreWarNotice();
		crossOreWarNotice.setNoticeUid(UUIDHelper.randomUUID(String.valueOf(userBaseInfo.getServerId())));
		crossOreWarNotice.setActivityId(crossUserOrePit.getActivityId());
		crossOreWarNotice.setPitId(crossUserOrePit.getPitId());
		crossOreWarNotice.setNoticeTime(System.currentTimeMillis() / 1000);
		crossOreWarNotice.setUserId(userId);
		crossOreWarNotice.setServerId(userBaseInfo.getServerId());
		crossOreWarNotice.setUserBaseInfo(userBaseInfo);
		//是空的情况就是占领空位置，这个时候就是空
		if(null == crossUserOrePit.getUserBaseInfo()){
			crossOreWarNotice.setEnemyUserId(0);
			crossOreWarNotice.setEnemyBaseInfo(new UserBaseInfo());
		}else {
			crossOreWarNotice.setEnemyUserId(crossUserOrePit.getUserId());
			crossOreWarNotice.setEnemyBaseInfo(crossUserOrePit.getUserBaseInfo());
		}
		return crossOreWarNotice;
	}

	//任务执行
	public void addTask(GeneralTask task) {
		threadTaskManger.addTask(actionId.getAndIncrement(), task);
	}
}